package org.deri.vor.mobilesensing.mobilesensor;


import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ListPeopleXMLParser {
    public final static String DEBUG = "ListPeopleXMLParser"; 
	
	public ArrayList <People> peopleList;
		
	public ListPeopleXMLParser(String url){
		
			
		 DocumentBuilderFactory builderFactory	=	DocumentBuilderFactory.newInstance();
	  	 try {
			 	peopleList	=	new ArrayList<People>();
		
			 	URL Url	=	new URL(url);
			 	
				DocumentBuilder builder				=	builderFactory.newDocumentBuilder();
				Document document					=	builder.parse(Url.openStream());
				document.getDocumentElement().normalize();
				Element rootElement							=	document.getDocumentElement();
				NodeList nodesSensor						=	rootElement.getChildNodes();
		        
		        for (int i=0; i< nodesSensor.getLength(); i++){
		        	String lat		= "";
		        	String lon		= "";
		        	String distance	= "";
		        	NodeList child = nodesSensor.item(i).getChildNodes();
		        	//==================================
		        	for (int j = 0; j<child.getLength();j++){
		        		if (child.item(j).getNodeName().equals("distance")) {
		        			distance = child.item(j).getFirstChild().getNodeValue();
		        		}
		        		
		        		if (child.item(j).getNodeName().equals("latitude")) {
		        			lat = child.item(j).getFirstChild().getNodeValue();
		        		}
		        		
		        		if (child.item(j).getNodeName().equals("longitude")) {
		        			lon = child.item(j).getFirstChild().getNodeValue();
		        		}
		        	}
		        	
		        	People people= new People(lat, lon, distance );
		        	peopleList.add(people);
		        }
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public class People{
		private int lon;
		private int lat;
		private String distance;
		
		public People(String lat,String lon, String distance){
			this.lat		=	(int)(Double.parseDouble(lat)*1e6);
			this.lon		=	(int)(Double.parseDouble(lon)*1e6);
			this.distance		=	distance;
		}
		
		public int getLat()				{return lat;}
		public int getLon()				{return lon;}
		public String getNumber()		{return distance;}
	}
}
